package com.GLM.Viewer.Party;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.GLM.Constants.Constant;
import com.GLM.Entity.MeetDataEntity;
import com.GLM.Entity.PartReviewEntity;
import com.GLM.Entity.PartyUsersEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.Image.AvatarUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Viewer.R;
import com.GLM.Viewer.R.string;
import com.GLM.Viewer.Users.UserInfoDetailActivity;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class PartyDetailActivity extends Activity {
	private String parentActivityString;
	private final static String TAG = "PartyDetailActivity";
	private final static int PARTYDETAIL_LOADING = 111;
	private final static int PARTYDETAIL_LONDED = 222;
    public String photoName;
	View mInputFieldMoreLines;
	EditText mInputFieldMoreLinesEditText;	
	Animation mAnimIn;
	Animation mAnimOut;
	InputMethodManager imm;
	private Bitmap mDrawableAvater;
	private String takePhotoPath;
	private String fromalbumPath;
	private boolean takePhoto = false;
	private boolean fromAlbum = false;
	private int mUserId;
	private MeetDataEntity mParty;
	Button btnImageView;
	private ListView mPersonsList;
	private SimpleAdapter mPersonsAdapter;
	private List<Map<String, Object>> mPersonsItems = new ArrayList<Map<String, Object>>();
	private String[] personItemKeys = new String[] { "person", "state","state_pic"};
	private int[] personItemIds = new int[] { R.id.party_journey_person, R.id.party_journey_state, R.id.party_journey_stateicon};
	private int meet_mg_id;
	private ListView mCommentsList;
	private SimpleAdapter mCommentsAdapter;
	private List<Map<String, Object>> mCommentsItems = new ArrayList<Map<String, Object>>();
	private String[] commentItemKeys = new String[] { "time", "content" };
	private int[] commentItemIds = new int[] { R.id.party_journey_comment_time, R.id.party_journey_com_content };
	private Map<String, String> commentPics = new HashMap<String, String>();
    private Map<Integer, Integer> comMap = new HashMap<Integer, Integer>();
	private AsynImageLoader imageLoader = new AsynImageLoader();
	ProgressDialog pd ;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Thread thread;
			
			
			switch (msg.what) {
			case PARTYDETAIL_LOADING:
				pd = ProgressDialog.show(PartyDetailActivity.this, "", getString(R.string.data_load), true, true);
				thread = new Thread(new Runnable() {
					public void run() {
						Looper.prepare();
						initPersonsAndCommentsList();
						mPersonsAdapter = new SimpleAdapter(PartyDetailActivity.this, mPersonsItems, R.layout.view_party_journey_personsitem, personItemKeys, personItemIds);
						mCommentsAdapter = new SimpleAdapter(PartyDetailActivity.this, mCommentsItems, R.layout.view_party_journey_commentsitem, commentItemKeys, commentItemIds);
						mHandler.sendEmptyMessage(PARTYDETAIL_LONDED);
						Looper.loop();
					}

				});
				
				thread.start();
				break;

			case PARTYDETAIL_LONDED:
				if(pd != null && pd.isShowing()){
					pd.cancel();
				}
				mPersonsList.setAdapter(mPersonsAdapter);
				mCommentsList.setAdapter(mCommentsAdapter);
				setListViewHeightBasedOnChildren(mPersonsList);
				initTitleData(mParty);
				bindItemClick();
				break;
			}
		}
	};
	private OnScrollListener scrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {

		}

		public void onScroll(AbsListView v, int firstVisibleItem, int visibleCount, int totalItemCount) {
			loadCommentsPics();
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_party_journey_itemdetail);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	
		Intent intent = getIntent();
		parentActivityString = intent.getStringExtra("ParentActivity");
		mParty = (MeetDataEntity) intent.getSerializableExtra("party");
		meet_mg_id = intent.getIntExtra("meet_mg_id", -1);
		bindButtonClick();
		mPersonsList = (ListView) findViewById(R.id.party_journey_personsListView);

		mCommentsList = (ListView) findViewById(R.id.party_journey_commentsListView);
		mCommentsList.setOnScrollListener(scrollListener);
		mUserId = UserInfoDAO.getUserInfo(this).getUserId();
		initInputFields();
		initAnimation();
		initRegisterInputFieldButton();
		mHandler.sendEmptyMessage(PARTYDETAIL_LOADING);
	}

	private void initPersonsAndCommentsList() {
		initPersonList();
		initCommentList();

	}

	private void initInputFields() {
		mInputFieldMoreLines = findViewById(R.id.inputfield_moreline);
		mInputFieldMoreLines.setVisibility(View.GONE);
		mInputFieldMoreLinesEditText = (EditText) findViewById(R.id.inputfieldmoreline_edittext);
		
	}

	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
	}
	
	private void initRegisterInputFieldButton() {
		// more line
		btnImageView = (Button)findViewById(R.id.comment_image_button);
		btnImageView.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(PartyDetailActivity.this);
				builder.setPositiveButton(getString(R.string.avater_album), new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
						intent.addCategory(Intent.CATEGORY_OPENABLE);
						intent.setType("image/*");
						startActivityForResult(Intent.createChooser(intent, "Selete Picture"), Constant.ACTIVITY_REQUESTCODE_ALBUM);
					}
				});
				builder.setNeutralButton(getString(R.string.avater_takepicture), new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						startActivityForResult(intent, Constant.ACTIVITY_REQUESTCODE_TAKEPICTURE);
					}
				});
				builder.setNegativeButton(getString(R.string.cancel), null);
				builder.setTitle(getString(R.string.newparty_tips_dialog));
				builder.show();
			}
		});
		Button inputMoreLineCancelButton = (Button) findViewById(R.id.inputfieldmoreline_cancelbutton);
		inputMoreLineCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideMoreLinesInputField();
			}
		});

		Button inputMoreLineOkButton = (Button) findViewById(R.id.inputfieldmoreline_okbutton);
		inputMoreLineOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String comContext = mInputFieldMoreLinesEditText.getText().toString().trim();
			
				if(!comContext.equals("")){
					hideMoreLinesInputField();
					
					try {
						if(takePhoto || fromAlbum)
							uploadFile();
						
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					initComment(comContext);
					mCommentsItems.clear();
					commentPics.clear();
					comMap.clear();
					initCommentList();
					mCommentsAdapter = new SimpleAdapter(PartyDetailActivity.this, mCommentsItems, R.layout.view_party_journey_commentsitem, commentItemKeys, commentItemIds);
					mCommentsList.setAdapter(mCommentsAdapter);
				}
			}
		});
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(resultCode == RESULT_OK){
			switch (requestCode) {
			case Constant.ACTIVITY_REQUESTCODE_ALBUM:
				String str = checkImagePath(data);
				if(str != null){
					takePhoto = false;
					fromAlbum = true;
					String end = str.substring(str.lastIndexOf("."));
					int endindex = str.lastIndexOf("/")+1;
					String fpath = str.substring(0, endindex);
					File file = new File(str);
					String filename = formatDatetime(new Date(), "yyyyMMddHHmmsssss")+end;
					File newFile = new File(fpath+filename);
					file.renameTo(newFile);
					
					fromalbumPath = newFile.getAbsolutePath();
					Log.d("fromalbum", fromalbumPath);
					photoName = filename;
					Log.d("photoName", photoName);
					Log.d("ImageChoosepath", str);
				}
				startPhotoZoom(data.getData());
				break;
			case Constant.ACTIVITY_REQUESTCODE_TAKEPICTURE:
				String status = Environment.getExternalStorageState();
				if(!status.equals(Environment.MEDIA_MOUNTED)){
					Toast.makeText(PartyDetailActivity.this, getString(R.string.sdcard_notin), Toast.LENGTH_LONG).show();
					return ;
				}
				Uri uri = data.getData();
				if(uri != null){
					mDrawableAvater = BitmapFactory.decodeFile(uri.getPath());
				}
				if(mDrawableAvater == null){
					Bundle bundle = data.getExtras();
					if(bundle != null){
						mDrawableAvater =  (Bitmap)bundle.get("data");
					}else{
						Toast.makeText(PartyDetailActivity.this, "获取照片失败", Toast.LENGTH_LONG).show();
						return;
					}
				}
				
				FileOutputStream outputStream = null;
				photoName = formatDatetime(new Date(), "yyyyMMddHHmmsssss")+".jpg";
				String dirstr = Environment.getExternalStorageDirectory().toString() +"/glemei";
				File dir = new File(dirstr);
				
				if (!dir.exists()) {
					dir.mkdir(); 
				}
				File file = new File(dirstr, photoName);
				try {
					file.createNewFile();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				takePhotoPath = file.getAbsolutePath();
				Log.d("takePhotoPath", takePhotoPath);
				try {
					outputStream = new FileOutputStream(takePhotoPath);
					mDrawableAvater.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
				Log.d("beginWriteImage", "begin");
				WriteImage();
				takePhoto = true;
				fromAlbum = false;
				btnImageView.setBackgroundDrawable(AvatarUtil.Bitmap2Drawable(mDrawableAvater));
				
				break;
			case Constant.ACTIVITY_REQUESTCODE_NEWAVATER:
				Drawable newAvater = getNewAvater(data);
				
				if (newAvater != null) {
					mDrawableAvater = ((BitmapDrawable) newAvater).getBitmap();
					btnImageView.setCompoundDrawables(newAvater, null, null, null);
				}
				break;	
			case Constant.PARTY_HISTORY_REBUILDPARTY:
				Bundle bd = data.getExtras();
				if(bd != null){
					int qstatus = bd.getInt("status");
					if(qstatus == 1){
						Toast.makeText(PartyDetailActivity.this, getString(R.string.party_rebuild_success), Toast.LENGTH_LONG).show();
					}
				}
				break;
			default:
				break;
			}
		}
		
	}
	
	 public void WriteImage() {  
	        try {  
	            FileInputStream fis = new FileInputStream(takePhotoPath);  
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
	            byte[] buffer = new byte[8192];  
	            int count = 0;  
	            while ((count = fis.read(buffer)) >= 0) {  
	                baos.write(buffer, 0, count);  
	  
	            }  
	            fis.close(); 
	            
	        } catch (FileNotFoundException e) {  
	            e.printStackTrace();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	 }  
	
	 
	public void uploadFile() throws ClientProtocolException, IOException{
		File file = null;
		
		if(takePhoto){
			file = new File(takePhotoPath);
		}
		if(fromAlbum){
			file = new File(fromalbumPath);
		}
		
		 try {
//			 	URL url = new URL("http://192.168.3.100:8088/phpProject/push/android_upload.php?filename="+photoName);
	            URL url = new URL(Constant.URL_PARTY_COMMENT +"?filename="+photoName);
	            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
	            httpUrlConnection.setDoOutput(true);
	            httpUrlConnection.setDoInput(true);
	            httpUrlConnection.setUseCaches(false);
	            httpUrlConnection.setRequestMethod("POST");
	            OutputStream os = httpUrlConnection.getOutputStream();
	            Thread.sleep(100);
	            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));

	            int bufSize = 0;
	            byte[] buffer = new byte[1024];
	            while ((bufSize = fis.read(buffer)) != -1) {
	                os.write(buffer, 0, bufSize);
	            }
	            fis.close();

	            String responMsg = httpUrlConnection.getResponseMessage();
	            Log.d(TAG, "responMsg =====" + responMsg);
	        } catch (Exception e) {
	           e.printStackTrace();
	        }
	
	}
	
	private String checkImagePath(Intent data){
		Cursor cursor = null;
		String path = null;
		try {
			Uri originalUri = data.getData();
			path = originalUri.toString();
			String[] proj = { MediaStore.Images.Media.DATA };
			cursor = managedQuery(originalUri, proj, null, null, null);
			if (cursor != null) {
				int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				// 最后根据索引值获取图片路径
				path = cursor.getString(column_index);
				Log.d("checkImagePath_path", path);
			}
		}
	    catch (Exception e) {
			Log.e("checkImage", e.getMessage());
		} finally {
			if (cursor != null && !cursor.isClosed()) 
				cursor.close();
		}
		
		return path;		
	}
	
	public static String formatDatetime(Date date, String format) {  
        DateFormat df = new SimpleDateFormat(format);  
        return df.format(date);  
    }  
	
	private Drawable getNewAvater(Intent data) {
		if (null != data) {
			Bundle bundle = data.getExtras();
			if (null != bundle) {
				Bitmap photo = bundle.getParcelable("data");
				
				Drawable drawable = new BitmapDrawable(photo);
				drawable.setBounds(0, 0, 100, 100);
				return drawable;
			}
		}
		return null;

	}
	
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, Constant.ACTIVITY_REQUESTCODE_NEWAVATER);
	}
	private void showMoreLinesInputField() {
		mInputFieldMoreLines.startAnimation(mAnimIn);
		mInputFieldMoreLines.setVisibility(View.VISIBLE);
		mInputFieldMoreLinesEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}
	
	private void hideMoreLinesInputField() {
		mInputFieldMoreLinesEditText.setText("");
		mInputFieldMoreLinesEditText.clearFocus();
		mInputFieldMoreLines.startAnimation(mAnimOut);
		mInputFieldMoreLines.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}
	
	private void initTitleData(MeetDataEntity mParty){
		TextView tvAddName = (TextView)findViewById(R.id.party_journey_addname);
		TextView tvPartyDate = (TextView)findViewById(R.id.party_journey_date);
		TextView tvBuildState = (TextView)findViewById(R.id.party_journey_buildstate);
		TextView tvPartyName = (TextView)findViewById(R.id.party_journey_name);
		TextView tvBuildName = (TextView)findViewById(R.id.party_journey_buildperson);
		tvAddName.setText(mParty.getMg_name());
		String partyDate = mParty.getMeet_createDate();
		String[] strs = partyDate.split(" ");
		String datestr = String.format(getString(R.string.dateformate), strs[2],strs[1],strs[0],strs[3]);
		tvPartyDate.setText(datestr);
		tvBuildState.setText(getString(R.string.journey_party_buildstate));
		
		tvPartyName.setText(mParty.getMeet_name());
		tvBuildName.setText(getString(R.string.journey_party_buildname)+mParty.getCreater_nickname());
	}
	
	public void initComment(String mCommentString){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		
		try {
			int user_id = UserInfoDAO.getUserInfo(PartyDetailActivity.this).getUserId();
			jsonData.put(Constant.PARAM_USERID, user_id);
			if(takePhoto || fromAlbum){
				jsonData.put("picture", photoName);
			}
			jsonData.put("content", mCommentString);
			jsonData.put("meet_id", meet_mg_id);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_COMMENTPARTY , jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if(status == 2){
					Toast.makeText(PartyDetailActivity.this, "评论成功", Toast.LENGTH_LONG).show();
				}else {
					Toast.makeText(PartyDetailActivity.this, "评论失败", Toast.LENGTH_LONG).show();
				}
			}
		} catch (Exception e) {
			// TODO: handle exception

		}
	}
	
	private void bindItemClick(){
		mCommentsList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long id) {
				// TODO Auto-generated method stub
				int com_userid = comMap.get(position);
				Log.d("com_userid",com_userid+"");
				Intent intent = new Intent(PartyDetailActivity.this, UserInfoDetailActivity.class);
				intent.putExtra(Constant.INTENT_USER_ID, com_userid);
				startActivity(intent);
				
			}
		});
		
		mPersonsList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long id) {
				// TODO Auto-generated method stub
				int mperson_id = mParty.getMeet_enlist()[position];
				Intent intent = new Intent();
				intent.putExtra(Constant.INTENT_USER_ID, mperson_id);
				intent.setClass(PartyDetailActivity.this, UserInfoDetailActivity.class);
				startActivity(intent);
			}
		});
		
	}
	
	private void initPersonList() {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_USERID, mUserId);
			jsonData.put("meet_id", mParty.getMeet_id());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETPARTYUSERS, jsonData);

			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_PARTY_USERS);
					initPersonsFromJSONObject(jsonArray);
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void initPersonsFromJSONObject(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			PartyUsersEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), PartyUsersEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();

			item.put("person", entity.getUd_nickname());
			State state = getStateByStateCode(entity.getEnl_state());
			item.put("state", state.getStateStr());
			item.put("state_pic", state.getStatePic());
			mPersonsItems.add(item);
		}

	}

	
	private State getStateByStateCode(int stateCode) {
		State state = new State();
		switch (stateCode) {
		case 1:
			state.setStateStr(getString(R.string.party_organizer));
			state.setStatePic(R.drawable.fparty_choose_yes);
			break;
		case 2:
			state.setStateStr(getString(R.string.party_waitting));
			state.setStatePic(R.drawable.fparty_state_wait);
			break;
		case 3:
			state.setStateStr(getString(R.string.party_accepted));
			state.setStatePic(R.drawable.fparty_choose_yes);
			break;
		case 4:
			state.setStateStr(getString(R.string.party_deny));
			state.setStatePic(R.drawable.fparty_state_no);
			break;
		default:
			break;
		}
		return state;
	}

	private void initCommentList() {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_USERID, mUserId);
			jsonData.put("meet_id", mParty.getMeet_id());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETPARTYCOMMENTS, jsonData);

			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_PARTY_COMMENTS);
					initCommentsFromJSONObject(jsonArray);
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void initCommentsFromJSONObject(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			PartReviewEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), PartReviewEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			String key = entity.getMr_user_nickname() + " - " + entity.getMr_date();
			item.put("time", key);
			item.put("content", entity.getMr_content());
			
			mCommentsItems.add(item);
			commentPics.put(key, entity.getMr_picture());
			comMap.put(i, entity.getMr_user_id());
		}

	}

	protected void loadCommentsPics() {
		int count = mCommentsList.getChildCount();
		for (int i = 0; i < count; i++) {
			View view = mCommentsList.getChildAt(i);
			TextView textview = (TextView) view.findViewById(R.id.party_journey_comment_time);
			String key = textview.getText().toString();
			if (i % 2 == 0) {
				textview.setBackgroundResource(R.drawable.freviews_right_top);
				textview.setGravity(Gravity.LEFT);
				textview.setPadding(20, 0, 0, 0);
			} else {
				textview.setBackgroundResource(R.drawable.freviews_left_top);
				textview.setGravity(Gravity.RIGHT);
				textview.setPadding(0, 0, 20, 0);
				
			}
			ImageView imageview = (ImageView) view.findViewById(R.id.party_journey_com_pic);
			String url = commentPics.get(key);
			if (url != null) {
				imageLoader.showImageAsyn(imageview, Constant.URL_MESSAGEPIC_SMALL + url, R.drawable.glm_white);
			}
		}
		mCommentsList.invalidate();

	}

	public void setListViewHeightBasedOnChildren(ListView listView) {  
	    ListAdapter listAdapter = listView.getAdapter();   
	    if (listAdapter == null) {  
	        return;  
	    }  

	    int totalHeight = 0;  
	    for (int i = 0; i < listAdapter.getCount(); i++) {  
	        View listItem = listAdapter.getView(i, null, listView);  
	        listItem.measure(0, 0);  
	        totalHeight += listItem.getMeasuredHeight();  
	    }  

	    ViewGroup.LayoutParams params = listView.getLayoutParams();  
	    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));  
	    ((MarginLayoutParams)params).setMargins(10, 10, 0, 10);
	    listView.setLayoutParams(params);  
	} 
	
	
	
	public void gobackButton_OnClick(View v){
		if(parentActivityString != null){
			if(parentActivityString.equals("PartyHistoryActivity")){
				NavUtils.navigateUpTo(PartyDetailActivity.this, new Intent(PartyDetailActivity.this,PartyHistoryActivity.class));
			}else if(parentActivityString.equals("PartyJourneyActivity")){
				NavUtils.navigateUpTo(PartyDetailActivity.this, new Intent(PartyDetailActivity.this,PartyJourneyActivity.class));
			}
		}else{
			
		}
	}
	
	public void bindButtonClick(){
		Button buildButton = (Button)findViewById(R.id.party_journey_buildagain);
		Button commentButton = (Button)findViewById(R.id.party_journey_comment);
		Button showMenButton = (Button)findViewById(R.id.party_journey_showmember);
		Button showComButton = (Button)findViewById(R.id.party_journey_showcomment);
		buildButton.setOnClickListener(clickListeners);
		commentButton.setOnClickListener(clickListeners);
		showMenButton.setOnClickListener(clickListeners);
		showComButton.setOnClickListener(clickListeners);
	}
	
    
	
	OnClickListener clickListeners = new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.party_journey_buildagain:
				Intent buildParty = new Intent(PartyDetailActivity.this,CreateNewPartyTimeViewActivity.class);
				buildParty.putExtra("parentIntent", "PartyDetailActivity");
				buildParty.putExtra("party", mParty);
				buildParty.putExtra("meet_mg_id", meet_mg_id);
				Log.d("PartyDetailActivity", meet_mg_id+"");
				startActivityForResult(buildParty, Constant.PARTY_HISTORY_REBUILDPARTY);
				break;
			case R.id.party_journey_comment:
				showMoreLinesInputField();
				break;
			case R.id.party_journey_showmember:
				mCommentsList.setVisibility(View.GONE);
				mPersonsList.setVisibility(View.VISIBLE);
				setListViewHeightBasedOnChildren(mPersonsList);
				break;
			case R.id.party_journey_showcomment:
				mPersonsList.setVisibility(View.GONE);
				mCommentsList.setVisibility(View.VISIBLE);
				setListViewHeightBasedOnChildren(mCommentsList);
				break;
			
			default:
				break;
			}
		}
	};
	
	
	
	class State {
		private String stateStr;
		private int statePic;

		public String getStateStr() {
			return stateStr;
		}

		public void setStateStr(String stateStr) {
			this.stateStr = stateStr;
		}

		public int getStatePic() {
			return statePic;
		}

		public void setStatePic(int statePic) {
			this.statePic = statePic;
		}

	}
	
	
}
